<template>
    <div class="course-container">
        <FilterSearch
            :searchItems="searchItems"
            :showAddButton="showAddButton"
            @query="handleQuery"
            @add="handleAdd"
        />
        <AutoTable
            :tableData="tableData"
            :columns="columns"
            @operate="handleOperate"
        />
        <Pagination
            :total="total"
            :pageSize="pageSize"
            :currentPage="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <MulitDrawer
            ref="mulitDrawerRef"
            :visible="editDialogVisible"
            :dialogType="editDialogType"
            :editItems="editItems"
            @successCallBack="editCallBack"
            @close="handleClose"
        />
    </div>
</template>
<script setup>
import './index.css';
import { reactive, ref, markRaw } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { View, Delete, Edit, Sort } from '@element-plus/icons-vue'

import FilterSearch from '@/components/filterSearch/index.vue';
import AutoTable from '@/components/autoTable/index.vue';
import Pagination from '@/components/pagination/index.vue';
import MulitDrawer from '@/components/mulitDrawer/index.vue';

import { courseApi } from '@/api';

// FilterSearch params
const searchItems = ref([
    {
      label: '标题',
      vModel: 'title',  
      type: 'input',
      initialValue: ''
    },
    {
      label: '课程分类',
      vModel: 'category',
      type: 'select',
      optionsCode: 'course_category',
      initialValue: ''
    },
    {
      label: '课程难度',
      vModel: 'difficulty',
      type: 'select',
      optionsCode: 'course_difficulty',
      initialValue: ''
    },
    {
      label: '课程状态',
      vModel: 'status',
      type: 'select',
      optionsCode: 'course_status',
      initialValue: ''
    }
]);  
const showAddButton = ref(true);
const searchCache = ref({});


// AutoTable params
const tableData = ref([]);
const columns = ref([
    {
      label: '标题',
      prop: 'title',
      width: '140px'
    },
    {
      label: '课程分类',
      prop: 'category',
      type: 'select',
      optionsCode: 'course_category',
      width: '180px'
    },
    {
      label: '课程难度',
      prop: 'difficulty',
      type: 'select',
      optionsCode: 'course_difficulty',
      width: '180px'
    },
    {
      label: '课程状态',
      prop: 'status',
      type: 'select',
      optionsCode: 'course_status',
      width: '180px'
    },
    {
      label: '描述',
      prop: 'description',
      width: '180px'
    },
    {
      label: '创建人',
      prop: 'instructor_name',
    },
    {
      label: '价格',
      prop: 'price',
    },
    {
      label: '折扣价格',
      prop: 'discount_price',
      width: '120px'
    },
    {
      label: '课程时长(分钟)',
      prop: 'duration',
      width: '140px',
    },
    {
        label: '课程标签',
        prop: 'tags',
        type: 'tag',
        width: '140px',
        getTag: item =>item.split(':')[0],
        getTips: item =>item.split(':')[0],
    },
    {
      label: '操作',
      prop: 'operate',
      fixed: 'right',
      type: 'action',
      align: 'left',
      width: '180px',
      operate: [
        {label: '详情', type: 'view', icon: markRaw(View)},
        {label: '编辑', type: 'edit', icon: markRaw(Edit)}, 
        {label: '删除', type: 'delete', icon: markRaw(Delete)},
        {label: '上架/下架', type: 'sort', icon: markRaw(Sort)},
      ]
    }

]);

// Pagination params
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// edit Dialog params
const editDialogVisible = ref(false);
const editDialogType = ref('add');
const editItems = ref([
    {
        block: 'baseInfo',
        label: '基础信息',
        layout: 'form',
        items: [
            {
                label: 'id',
                vModel: '_id',
                type: 'forbidden',
                initialValue: '',
            },
            {
                label: '创建人',
                vModel: 'instructor',
                type: 'forbidden',
                initialValue: ''
            },
            {
                label: '标题',
                vModel: 'title',
                type: 'input',
                initialValue: ''
            },
            {
                label: '课程分类',
                vModel: 'category',
                type: 'select',
                optionsCode: 'course_category',
                initialValue: ''
            },
            {
                label: '课程难度',
                vModel: 'difficulty',
                type: 'select',
                optionsCode: 'course_difficulty',
                initialValue: ''
            },
            {
                label: '课程状态',
                vModel: 'status',
                type: 'select',
                optionsCode: 'course_status',
                forbidden: true,
                initialValue: ''
            },
            {
                label: '价格',
                vModel: 'price',
                type: 'input',
                initialValue: ''
            },
            {
                label: '折扣价格',
                vModel: 'discount_price',
                type: 'input',
                initialValue: ''
            },
            {
                label: '课程时长',
                vModel: 'duration',
                type: 'input',
                initialValue: ''
            },
            {
                label: '创建时间',
                vModel: 'created_time',
                forbidden: true,
                type: 'date',
                initialValue: ''
            },
            {
                label: '更新时间',
                vModel: 'updated_time',
                forbidden: true,
                type: 'date',
                initialValue: ''
            },
            {
                label: '描述',
                vModel: 'description',
                type: 'input',
                initialValue: ''
            },
        ]
    },
    {
        block: 'coverInfo',
        label: '封面信息',
        layout: 'form',
        items: [
            {
                label: '封面图片',
                vModel: 'cover_image',
                type: 'upload',
                action: () => `/sys/file/upload/course_image`,
                initialValue: ''
            },
            {
                label: '预览视频',
                vModel: 'preview_video',
                type: 'upload',
                fileType: 'video',
                action: () => `/sys/file/upload/course_video`,
                initialValue: ''
            },
            {
                label: '课程标签',
                vModel: 'tags',
                type: 'tag',
                initialValue: []
            },
            {
                label: '课程评分',
                vModel: 'average_rating',
                type: 'rate',
                forbidden: true,
                initialValue: 0,
            },
            {
                label: '报名人数',
                vModel: 'enrolled_count',
                type: 'input',
                forbidden: true,
                initialValue: ''
            },
        ]
    },
    {
        block: 'sections',
        label: '章节信息',
        layout: 'tabs',
        vModel: {
            tabPane: 'title',
            tabContain: 'lessons',
            cardName: 'lesson_title',
            cardUrl: 'video_url',
            cardSub: 'duration',
            cardResources: 'resources',
            resourcesName: 'name',
            resourcesUrl: 'url',
        },
        editItems: [
            {
                label: '课程标题',
                vModel: 'lesson_title',
                type: 'input',
                initialValue: ''
            },
            {
                label: '课程视频',
                vModel: 'video_url',
                type: 'upload',
                fileType: 'video',
                action: () => `/sys/file/upload/course_video`,
                initialValue: ''
            },
            {
                label: '课程时长(分钟)',
                vModel: 'duration',
                type: 'input',
                initialValue: ''
            },
            {
                label: '课程资源',
                vModel: 'resources',
                type: 'array',
                childItems: [
                  {
                    label: '索引',
                    vModel: 'resources',
                    type: 'forbidden',
                    initialValue: 'resources'
                  },
                  {
                    label: '资源名称',
                    vModel: 'name',
                    type: 'input',
                    initialValue: ''
                  },
                  {
                    label: '资源文件',
                    vModel: 'url',
                    type: 'upload',
                    fileType: 'video',
                    action: () => `/sys/file/upload/course_video`,
                    initialValue: ''
                  }
                ],
                initialValue: [],
            },
        ],
        initialValue: [],
    },
    {
        block: 'related_plans',
        label: '计划信息',
        layout: 'tabs',
        vModel: {
            tabPane: 'title',
            tabContain: 'lessons',
            cardName: 'lesson_title',
            cardUrl: 'video_url',
            cardSub: 'duration',
            cardResources: 'resources',
            resourcesName: 'name',
            resourcesUrl: 'url',
        },
        editItems: [
        ],
        initialValue: [],
    }
]);  
const initData = {
    // 基础信息部分
  _id: '',
  instructor: '',
  title: '',
  category: '',
  difficulty: '',
  status: 'draft',
  price: '',
  discount_price: '',
  duration: '',
  created_time: new Date(),
  updated_time: new Date(),
  description: '',
  
  // 封面信息部分
  cover_image: '',
  preview_video: '',
  tags: [],
  average_rating: 0,
  enrolled_count: 0,
  
  // 章节和计划信息
  sections: [],
  related_plans: []
}
// filterSearch Api
const handleQuery = async (params) => {
    // 调用接口获取数据
    searchCache.value = params;
    const reqParams = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        ...params
    }
    const res = await courseApi.getCourse(reqParams);
    if (res.code === 200) {
      tableData.value = res.data.rows;
      total.value = res.data.total;
    }
};

// EditDialog Api
const handleAdd = () => {
    editDialogType.value = 'add';
    initEditItems(initData);
    editDialogVisible.value = true;
};
const editCallBack = async (type, params) => {
    if (type === 'add') handleAddCallBack(params);
    else if (type === 'edit') handleEditCallBack(params);
} 
const handleAddCallBack = async (data) => {
    const params = {...data[0], ...data[1], sections: data[2], related_plans: data[3]};
    const res = await courseApi.createCourse(params);
    if (res.code === 200) {
        editDialogVisible.value = false;
        ElMessage.success('新增成功');
        handleQuery();
    }
}
const handleEditCallBack = async (params) => {
  const res = await courseApi.updateCourse(params[0]._id, {...params[0], ...params[1], sections: params[2], related_plans: params[3]});
  if (res.code === 200) {
    editDialogVisible.value = false;
    ElMessage.success('变更成功');
    handleQuery();
  }
}
const handleClose = () => {
    editDialogVisible.value = false;
}

// Pagination Api
const handleSizeChange = (size) => {
    pageSize.value = size;
    handleQuery(searchCache.value);
};
const handleCurrentChange = (page) => {
    currentPage.value = page;
    handleQuery(searchCache.value);

};

// AutoTable Api
const handleOperate = async (type, row) => {
    if (type === 'delete') {
      handleDelete(row);
      return ;
    }
    else if (type === 'sort') {
      handlePublish(row);
      return ;
    }
    const res = await courseApi.getCourseDetail(row._id);
    if(res.code !== 200){
      ElMessage.error(res.msg);
      return ;
    }
    if (type === 'edit') {
      editDialogType.value = 'edit';
      initEditItems(res.data);
      editDialogVisible.value = true;

    }
    else if (type === 'view') {
      editDialogType.value = 'view';
      initEditItems(res.data);
      editDialogVisible.value = true;
    }
}
const initEditItems = (row) => {
  editItems.value.forEach(item => {
    if(item.layout === 'tabs'){
        item.initialValue = row[item.block];
    }
    else if(item.layout === 'form') item.items.forEach(subItem => {
      subItem.initialValue = row[subItem.vModel];
    })
  })
}
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定删除当前课程吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await courseApi.deleteCourse(row._id)
      if (res.code === 200) {
        ElMessage({ type: 'success', message: '删除成功!' });
        handleQuery();
      }
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消删除!' })
    })
}
const handlePublish = (row) => {
  ElMessageBox.confirm(
    `确定${row.status === 'published' ? '下架' : '上架'}当前课程吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await courseApi.publishCourse(row._id)
      if (res.code === 200) {
        ElMessage({ type: 'success', message: `${row.status === 'published' ? '下架' : '上架'}成功!` });
        handleQuery();
      }
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消操作!' })
    })
}

</script>